<?php

/**
 * 后台菜单管理类
 *
 * @author suing <snsnsky@gmail.com>
 */

namespace Admin;

use \Common\Bridge;

class Menu
{
    /**
     * 获取所有菜单或用户有权限的所有菜单
     *
     * @param mixed $auth 注：auth是以菜单KEY为键名的数组，键值不作要求
     * @return array
     */
    public static  function getAllMenu($auth = false)
    {
        $db = Bridge::pdo(Bridge::DB_ADMIN_R);
        $data = $db->query("select * from AdminMenu where ParentId=0 order by DisplayOrder desc")->fetchAll();
        empty($data) && $first = [];
        $return = [];
        foreach ($data as $v)
        {
            $id = $v['AdminMenuId'];
            if (isset($auth[$v['Key']]) || !$auth)
            {
                $return[$id] = $v;
                $return[$id]['child'] = self::getMenuChild($id, $auth);
                foreach ($return[$id]['child'] as $key => $value)
                {
                    $cid = $value['AdminMenuId'];
                    $return[$id]['child'][$key]['child'] = self::getMenuChild($cid, $auth);
                }
            }
        }
        return $return;
    }

    /*
     * 获取菜单的下级子菜单，如果传递auth，则只返回auth中存在的菜单
     *
     * @param int id 菜单ID
     * @param mixed auth  注：auth是以菜单KEY为键名的数组，键值不作要求
     * @return array
     */
    public static  function getMenuChild($id, $auth = false)
    {
        $db = Bridge::pdo(Bridge::DB_ADMIN_R);
        $data = $db->query("select * from AdminMenu where ParentId={$id} order by DisplayOrder desc")->fetchAll();
        if ($auth)
        {
            foreach ($data as $k => $v)
            {
                if (!isset($auth[$v['Key']]))
                {
                    unset($data[$k]);
                }
            }
        }
        return empty($data) ? [] : $data;
    }

    /**
     * 根据菜单KEY返回菜单
     *
     * @param string $key  菜单KEY
     * @return array
     */
    public static  function getMenuByKey($key)
    {
        $db = Bridge::pdo(Bridge::DB_ADMIN_R);
        $data = $db->query("select * from AdminMenu where `Key`='{$key}'")->fetch();
        empty($data) && $data = [];
        return $data;
    }
}